import { cloumsDelte, cloumsGet } from '@/services/colums';
import { PlusOutlined, ExportOutlined } from '@ant-design/icons';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Tag } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { keyBy } from 'lodash';
import CloumsPage from './components/CloumsPage';
import { downloadExcel } from '@/utils/excelUtils';

/**
 *  Delete nodes
 * @zh-CN 批量删除节点
 * @param selectedRows
 */
const handleRemoves = async (selectedRows: CLOUMS.CLOUMSListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await Promise.all(selectedRows.map((row) => cloumsDelte({ code: row.code })));
    return true;
  } catch (error: any) {
    return false;
  } finally {
    hide();
  }
};

const CloumsList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   **/
  const [currentRow, setCurrentRow] = useState<CLOUMS.CLOUMSListItem>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * 设定页面类型
   * 1. 新增指标
   * 2. 修改指标
   * 3. 查看指标
   **/
  const [pageType, setPageType] = useState<number>();

  // 设置
  const [indicatorData, setIndicatorData] = useState<CLOUMS.CLOUMSListItem[]>();

  // 指标类型转态配置项
  const CLOUMNS_STATUS_OPTION = [
    { text: '基础指标', value: '1', color: 'blue' },
    { text: '必要指标', value: '2', color: 'pink' },
    { text: '自定义指标', value: '3', color: 'green' },
  ];
  // 类型枚举 标签属性
  const requestStatusEnum = keyBy(CLOUMNS_STATUS_OPTION, 'value');

  /* 获取所有的指标 */
  const getCloumsData = () => {
    cloumsGet({}).then((res) => {
      setIndicatorData(res.data);
    });
  };

  // 更新指标数据
  useEffect(() => {
    getCloumsData();
  }, []);

  const actionRef = useRef<ActionType>();

  // : ProColumns<CLOUMS.CLOUMSListItem[], "text">[] | undefined 可能为空
  const columns: ProColumns<CLOUMS.CLOUMSListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      hideInSearch: true,
      width: 45,
    },
    {
      title: '指标名称',
      dataIndex: 'name',
    },
    {
      title: '指标编码',
      dataIndex: 'code',
      tip: '指标编码是唯一的',
      // sorter: true,
    },
    {
      title: '指标类型',
      dataIndex: 'type',
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      valueEnum: requestStatusEnum,
      render: (_text, { type }) => {
        const tagStatus = requestStatusEnum[type] || { color: '', text: '未知' };
        return <Tag color={tagStatus.color}>{tagStatus.text}</Tag>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Button
          type="link"
          key="modify"
          onClick={() => {
            setCurrentRow(record);
            setPageType(2);
            handleModalVisible(true);
          }}
        >
          修改
        </Button>,
        <Button
          type="link"
          key="detail"
          onClick={() => {
            setCurrentRow(record);
            setPageType(3);
            handleModalVisible(true);
          }}
        >
          详情
        </Button>,
        record.type === '3' ? (
          <Popconfirm
            key="delete"
            placement="topLeft"
            title={'删除'}
            onConfirm={() => {
              handleRemoves([record]);
              /* 重新渲染页面 */
              actionRef.current?.reload();
            }}
            okText="确认"
            cancelText="取消"
          >
            <Button type="link">删除</Button>
          </Popconfirm>
        ) : (
          ''
        ),
      ],
    },
  ];

  // Excel 导出方法
  function onExportExcel() {
    downloadExcel({
      filename: '指标数据',
      sheets: [
        {
          sheetName: 'test',
          columns: columns,
          dataSource: indicatorData,
        },
      ],
    });
  }

  return (
    <PageContainer>
      <ProTable<CLOUMS.CLOUMSListItem, CLOUMS.CLOUMSParams>
        actionRef={actionRef}
        rowKey="code"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              /* 不加 undefined 会有必填校验 */
              setCurrentRow(undefined);
              setPageType(1);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined />
            新增
          </Button>,
          <Button type="primary" key="export" onClick={() => onExportExcel()}>
            <ExportOutlined />
            导出
          </Button>,
        ]}
        request={cloumsGet}
        columns={columns}
        pagination={{
          pageSize: 10,
        }}
      />
      {createModalVisible ? (
        <CloumsPage
          pageType={pageType}
          pageData={currentRow}
          show={createModalVisible}
          showFn={handleModalVisible}
          reload={actionRef.current}
          indicatorData={indicatorData}
        />
      ) : (
        ''
      )}
    </PageContainer>
  );
};

export default CloumsList;
